<template>
  <div class="shop-list-container">
    <!-- 标题 -->
    <div class="page-title">信息管理</div>

    <!-- 筛选区域 -->
    <el-card class="filter-card" shadow="hover">
      <el-row :gutter="20" align="middle">
        <!-- 门店名称 -->
        <el-col :span="4">
          <el-input
              v-model="searchParams.shopName"
              placeholder="请输入门店名称"
              clearable
          />
        </el-col>
        <!-- 负责人联系方式 -->
        <el-col :span="4">
          <el-input
              v-model="searchParams.contact"
              placeholder="请输入联系方式"
              clearable
          />
        </el-col>
        <!-- 区域选择 -->
        <el-col :span="4">
          <el-select
              v-model="searchParams.region"
              placeholder="请选择查询的省/市/区县"
              clearable
          >
            <el-option label="北京市" value="北京市" />
            <el-option label="上海市" value="上海市" />
            <el-option label="广州市" value="广州市" />
          </el-select>
        </el-col>
        <!-- 入驻日期 -->
        <el-col :span="6">
          <el-date-picker
              v-model="searchParams.enterDate"
              type="daterange"
              range-separator="至"
              start-placeholder="入驻日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
          />
        </el-col>
        <!-- 门店状态 -->
        <el-col :span="4">
          <el-select
              v-model="searchParams.status"
              placeholder="请选择门店状态"
              clearable
          >
            <el-option label="全部" value="" />
            <el-option label="正常" value="1" />
            <el-option label="关闭" value="0" />
          </el-select>
        </el-col>
        <!-- 重置按钮 -->
        <el-col :span="1">
          <el-button @click="handleReset">重置</el-button>
        </el-col>
        <!-- 查询按钮 -->
        <el-col :span="1">
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新建门店按钮（右上角） -->
    <div class="create-shop-btn" style="text-align: right; margin: 10px 0;">
      <el-button type="primary" @click="handleCreateShop">+ 新建门店</el-button>
    </div>


    <!-- 店铺列表 -->
    <el-card class="table-card" shadow="hover">
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          :loading="loading"
          @selection-change="handleSelectionChange"
      >
        <!-- 多选框 -->
        <el-table-column type="selection" width="55" />
        <!-- 编号 -->
        <el-table-column prop="id" label="编号" width="80" />
        <!-- 门店名称 -->
        <el-table-column prop="shopName" label="门店名称" min-width="120" />
        <!-- 商家地址 -->
        <el-table-column prop="address" label="商家地址" min-width="200" />
        <!-- 门店电话 -->
        <el-table-column prop="shopPhone" label="门店电话" width="150" />
        <!-- 负责人 -->
        <el-table-column prop="manager" label="负责人" width="100" />
        <!-- 联系电话 -->
        <el-table-column prop="contactPhone" label="联系电话" width="150" />
        <!-- 创建时间 -->
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <!-- 更新时间 -->
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <!-- 启用状态 -->
        <el-table-column prop="status" label="启用状态" width="120">
          <template #default="scope">
            <el-switch
                v-model="scope.row.status"
                active-value="1"
                inactive-value="0"
                @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
                type="text"
                text-color="#409EFF"
                @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
                type="text"
                text-color="#f56c6c"
                @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 20px; text-align: right;"
      />
    </el-card>
    <!-- 编辑门店弹窗 -->
    <el-dialog
        v-model="editDialogVisible"
        title="编辑门店信息"
        width="50%"
        :before-close="handleEditDialogClose"
    >
      <el-form
          :model="editForm"
          :rules="editRules"
          ref="editFormRef"
          label-width="120px"
      >
        <el-form-item label="门店名称" prop="shopName">
          <el-input v-model="editForm.shopName" placeholder="请输入门店名称" />
        </el-form-item>
        <el-form-item label="商家地址" prop="address">
          <el-input v-model="editForm.address" placeholder="请输入商家地址" />
        </el-form-item>
        <el-form-item label="门店电话" prop="shopPhone">
          <el-input v-model="editForm.shopPhone" placeholder="请输入门店电话" />
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="editForm.manager" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="editForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-switch
              v-model="editForm.status"
              active-value="1"
              inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditDialogClose">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit">确认修改</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除"
        width="30%"
    >
      <div class="delete-confirm-content">
        确定要删除 <span class="delete-shop-name">{{ deleteShopName }}</span> 吗？
        <p class="delete-tip">此操作不可恢复，请谨慎处理。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleDeleteConfirm">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, reactive, watch} from 'vue';
import { useRouter } from 'vue-router';
import {ElMessage} from "element-plus";

const router = useRouter();

// 搜索参数
const searchParams = ref({
  shopName: '',
  contact: '',
  region: '',
  enterDate: [],
  status: ''
});

// 表格数据（模拟与目标页面一致的数据）
const tableData = ref([
  {
    id: '120',
    shopName: '海底捞-世纪金源店',
    address: '远大路1号世纪金源购物中心西区F5',
    shopPhone: '01088878876',
    manager: '李大帅',
    contactPhone: '12145003392',
    createTime: '2024-06-07 09:22:15',
    updateTime: '2024-06-07 09:22:15',
    status: true
  },
  {
    id: '119',
    shopName: '海底捞-圣熙店',
    address: '北京市海淀区花园东路2号牡丹宾馆北',
    shopPhone: '010 6203 3112',
    manager: '闫振宇',
    contactPhone: '13311003392',
    createTime: '2024-06-07 09:19:52',
    updateTime: '2024-06-07 09:19:52',
    status: true
  },
  {
    id: '118',
    shopName: '海底捞石景山店',
    address: '海底捞石景山店喜隆多',
    shopPhone: '6789012',
    manager: '小花花',
    contactPhone: '432112345',
    createTime: '2024-06-05 02:33:31',
    updateTime: '2024-06-05 02:33:31',
    status: true
  },
  {
    id: '117',
    shopName: '圣熙8号店',
    address: '北京市海淀区',
    shopPhone: '18811223456',
    manager: '张三',
    contactPhone: '19919888123',
    createTime: '2024-06-05 02:26:25',
    updateTime: '2024-06-05 02:26:25',
    status: true
  },
  {
    id: '116',
    shopName: '海底捞万柳书院门店',
    address: '万柳书院院店',
    shopPhone: '18702836102',
    manager: '小花花',
    contactPhone: '18702836102',
    createTime: '2024-06-05 01:21:21',
    updateTime: '2024-06-05 01:21:21',
    status: true
  }
]);

// 分页参数
const currentPage = ref(1);  // 当前页
const pageSize = ref(10);   // 每页条数
const total = ref(tableData.value.length); // 总条数（模拟）

// 加载状态
const loading = ref(false);

// 初始化：获取列表数据
onMounted(() => {
  fetchTableData();
});

// 获取表格数据（模拟，实际替换为接口请求）
const fetchTableData = () => {
  loading.value = true;
  // 模拟接口延迟
  setTimeout(() => {
    // 实际逻辑：调用接口，替换 tableData
    // axios.post('/api/shop/list', {
    //   ...searchParams.value,
    //   page: currentPage.value,
    //   size: pageSize.value
    // }).then(res => {
    //   tableData.value = res.data.records;
    //   total.value = res.data.total;
    // }).finally(() => loading.value = false);
    loading.value = false;
  }, 500);
};
// 监听静态查询类型变化


// 应用静态查询
const applyStaticQuery = (type) => {
  // 重置分页
  currentPage.value = 1;

  // 根据不同的静态查询类型设置搜索参数
  switch(type) {
    case 'all':
      searchParams.value = {
        shopName: '',
        contact: '',
        region: '',
        enterDate: [],
        status: ''
      };
      break;
    case 'active':
      searchParams.value = {
        shopName: '',
        contact: '',
        region: '',
        enterDate: [],
        status: '1' // 正常营业
      };
      break;
    case 'inactive':
      searchParams.value = {
        shopName: '',
        contact: '',
        region: '',
        enterDate: [],
        status: '0' // 已关闭
      };
      break;
    case 'today':
      // 设置今日日期范围
      const today = new Date();
      const todayStr = today.toISOString().split('T')[0];
      searchParams.value = {
        shopName: '',
        contact: '',
        region: '',
        enterDate: [todayStr, todayStr], // 今日
        status: ''
      };
      break;
  }

  // 执行查询
  fetchTableData();
};

// 编辑弹窗相关
const editDialogVisible = ref(false);
const editForm = reactive({
  id: '',
  shopName: '',
  address: '',
  shopPhone: '',
  manager: '',
  contactPhone: '',
  status: ''
});
const editFormRef = ref(null);
const editRules = {
  shopName: [{ required: true, message: '请输入门店名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入商家地址', trigger: 'blur' }],
  shopPhone: [
    { required: true, message: '请输入门店电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

// 删除弹窗相关
const deleteDialogVisible = ref(false);
const deleteShopId = ref('');
const deleteShopName = ref('');
// 查询
const handleSearch = () => {
  currentPage.value = 1; // 查询后重置页码
  applyStaticQuery();
  fetchTableData();
};

// 重置
const handleReset = () => {
  searchParams.value = {
    shopName: '',
    contact: '',
    region: '',
    enterDate: [],
    status: ''
  };
  currentPage.value = 1;
  fetchTableData();
};

// 多选框改变
const handleSelectionChange = (val) => {
  console.log('选中的门店：', val);
  // 可扩展批量操作逻辑
};



// 新建门店
const handleCreateShop = () => {
  router.push({ name: 'xv' });
};

// 编辑门店
const handleEdit = (row) => {
  // 填充编辑表单数据
  editForm.id = row.id;
  editForm.shopName = row.shopName;
  editForm.address = row.address;
  editForm.shopPhone = row.shopPhone;
  editForm.manager = row.manager;
  editForm.contactPhone = row.contactPhone;
  editForm.status = row.status ? '1' : '0';

  // 显示编辑弹窗
  editDialogVisible.value = true;
};

// 编辑弹窗关闭
const handleEditDialogClose = () => {
  editFormRef.value?.resetFields();
  editDialogVisible.value = false;
};

// 编辑提交
const handleEditSubmit = () => {
  editFormRef.value?.validate((valid) => {
    if (valid) {
      // 模拟接口请求
      setTimeout(() => {
        ElMessage.success('修改成功');
        editDialogVisible.value = false;
        fetchTableData(); // 刷新列表
      }, 500);
    }
  });
};
// 删除门店
const handleDelete = (row) => {
  deleteShopId.value = row.id;
  deleteShopName.value = row.shopName;
  deleteDialogVisible.value = true;
};

// 删除确认
const handleDeleteConfirm = () => {
  // 模拟接口请求
  setTimeout(() => {
    deleteDialogVisible.value = false;
    ElMessage.success('删除成功');
    // 过滤表格数据
    tableData.value = tableData.value.filter(item => item.id !== deleteShopId.value);
    total.value = tableData.value.length;
  }, 500);
};

// 状态切换
const handleStatusChange = (row) => {
  console.log('切换门店状态：', row);
  // 实际逻辑：调用接口更新状态
};


// 每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchTableData();
};

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchTableData();
};
</script>

<style scoped>
.shop-list-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 64px); /* 适配顶部导航高度 */
}

/* 标题样式 */
.page-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 10px 0 20px;
}

/* 筛选卡样式 */
.filter-card {
  padding: 20px;
  margin-bottom: 10px;
}

/* 表格卡样式 */
.table-card {
  padding: 20px;
}

/* 新建按钮样式 */
.create-shop-btn {
  margin-bottom: 10px;
}

/* 表格单元格样式优化 */
.el-table th, .el-table td {
  text-align: center;
}
</style>